package day_2022_7_to_8.day48;

import java.util.*;

/**
 * @author haomin
 * @date 2022/08/31 21:21
 **/
public class Day46_12_Offer32_Ⅲ_LevelOrder {
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        List<List<Integer>> res = new ArrayList<>();
        public List<List<Integer>> levelOrder(TreeNode root) {
            if(root == null) return new ArrayList<>();
            Queue<TreeNode> queue = new LinkedList<>();
            Stack<TreeNode> stack = new Stack<>();
            queue.offer(root);
            int flag = 0;
            while(!queue.isEmpty()){
                List<Integer> ret = new ArrayList<>();
                if(flag == 0){
                    int size = queue.size();
                    for(int i = 0;i < size; ++i){
                        TreeNode cur = queue.poll();
                        ret.add(cur.val);
                        if(cur.left != null) {
                            queue.offer(cur.left); stack.push(cur.left);}
                        if(cur.right != null) {
                            queue.offer(cur.right); stack.push(cur.right);}
                    }
                    res.add(ret); flag = 1;
                }else{
                    int size = queue.size();
                    for(int i = 0;i < size; ++i){
                        TreeNode cur = queue.poll();
                        if(cur.left != null) queue.offer(cur.left);
                        if(cur.right != null) queue.offer(cur.right);
                    }
                    while(!stack.isEmpty()){
                        TreeNode cur = stack.pop();
                        ret.add(cur.val);
                    }
                    res.add(ret); flag = 0;
                }
            }
            return res;
        }
    }
    class Solution2 {
        List<List<Integer>> res = new ArrayList<>();
        public List<List<Integer>> levelOrder(TreeNode root) {
            preOrder(root, 0);
            return res;
        }
        private void preOrder(TreeNode root, int k){
            if(root == null) return;
            if(res.size() <= k) res.add(new ArrayList<>());
            if(k % 2 == 0) res.get(k).add(root.val);
            else res.get(k).add(0, root.val);

            preOrder(root.left, k+1);
            preOrder(root.right, k+1);
        }
    }
}